package com.noble.meether.chat.ui.agora.manager;

import android.app.Activity;
import android.content.Context;
import android.support.v4.app.FragmentActivity;

import com.alibaba.fastjson.JSON;
import com.noble.glamour.module.logic.application.App;
import com.noble.glamour.module.logic.application.ModuleMgr;
import com.noble.glamour.module.logic.baseui.LoadingDialog;
import com.noble.glamour.module.logic.config.UrlParam;
import com.noble.glamour.module.logic.request.RequestComplete;
import com.noble.glamour.module.logic.socket.NetData;
import com.noble.glamour.module.logic.socket.listener.SendCallBack;
import com.noble.library.log.PToast;
import com.noble.library.observe.ModuleBase;
import com.noble.library.observe.MsgMgr;
import com.noble.library.observe.MsgType;
import com.noble.library.permission.PermissionUtil;
import com.noble.library.permission.callback.PermissionListener;
import com.noble.meether.chat.MessageConstant;
import com.noble.meether.chat.msgtype.CommonMessage;
import com.noble.meether.chat.ui.agora.RtcUIShow;
import com.noble.meether.chat.ui.agora.model.AgoraConstant;
import com.noble.meether.chat.ui.agora.model.EngineConfig;
import com.noble.meether.chat.ui.agora.util.RtcJointChannel;
import com.noble.meether.fragment.rob.RobMessage;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 音视频聊天相关管理类
 * <p>
 * Created by Su on 2017/10/28.
 */
public class RtcChatMgr implements ModuleBase {
    @Override
    public void init() {
    }

    @Override
    public void release() {
    }

    private int chatType;      // 通信类型  1为音频{@link # AgoraConstant.RTC_CHAT_VIDEO}，2为视频{@link # AgoraConstant.RTC_CHAT_VOICE}
    private int singleType = 1;    // 非默认情况值, 0:还没选择,1:自己露脸，2:自己不露脸

    /**
     * 邀请对方视频聊天
     */
    public void inviteVideo(final Activity context, final long dstUid) {
        //ModuleMgr.getNotifyMgr().playSound();
        if (ModuleMgr.getRtcEnginMgr().getEngineConfig().isBusy) {
            PToast.showShort("当前处于聊天中，无法发起新的聊天");
            return;
        }
        LoadingDialog.show((FragmentActivity) context, "发送中...");
        PermissionUtil.checkAVPermission(context, new PermissionListener() {
            @Override
            public void success() {
                chatType = AgoraConstant.RTC_CHAT_VIDEO;
                executeInviteChat(context, dstUid);
            }

            @Override
            public void fail() {
                LoadingDialog.closeLoadingDialog();
                PToast.showShort("未检测到音视频权限");
            }
        });
    }

    /**
     * 邀请对方音频通信
     */
    public void inviteVoice(final Activity context, final long dstUid) {
        //ModuleMgr.getNotifyMgr().playSound();
        if (ModuleMgr.getRtcEnginMgr().getEngineConfig().isBusy) {
            PToast.showShort("当前处于聊天中，无法发起新的聊天");
            return;
        }
        LoadingDialog.show((FragmentActivity) context, "发送中...");
        PermissionUtil.checkAVPermission(context, new PermissionListener() {
            @Override
            public void success() {
                chatType = AgoraConstant.RTC_CHAT_VOICE;
                executeInviteChat(context, dstUid);
            }
            @Override
            public void fail() {
                LoadingDialog.closeLoadingDialog();
                PToast.showShort("未检测到音视频权限");
            }
        });
    }

    /**
     * 打开被邀请时的页面
     *
     * @param dstUid   对方UID
     * @param chatType 1视频，2音频
     */
    public void openInvitedActivity(long dstUid, int chatType) {
        this.chatType = chatType;
        initEnginConfig(dstUid, AgoraConstant.RTC_CHAT_BEINVITE);
        RtcUIShow.showRtcInitAct(App.getContext());
    }

    /**
     * 发送音视频聊天消息
     */
    private void executeInviteChat(final Context context, final long dstUid) {
        initEnginConfig(dstUid, AgoraConstant.RTC_CHAT_INVITE);
        reqChatQualified(dstUid, response -> {
            if (!response.isOk()) {
                LoadingDialog.closeLoadingDialog();
                PToast.showShort(response.getMsg());
                return;
            }
            handleInviteChat(context, dstUid);
        });
    }

    private void handleInviteChat(final Context context, final long dstUid) {
        int msgType = chatType == AgoraConstant.RTC_CHAT_VOICE ?
                MessageConstant.MSG_ID_CHAT_AUDIO : MessageConstant.MSG_ID_CHAT_VIDEO;
        ModuleMgr.getChatMgr().sendAVMsg(dstUid, msgType, new SendCallBack() {
            @Override
            public void onResult(long msgId, long sender, String contents) {
                LoadingDialog.closeLoadingDialog();
            }

            @Override
            public void onSendFailed(NetData data) {
                LoadingDialog.closeLoadingDialog();
                PToast.showShort("邀请失败，请稍后重试");
            }
        });
    }

    /**
     * 直接开启聊天页
     */
    public void openInvitedDirect() {
        RtcJointChannel.getInstance().joinChannelPrepare(false);
        EngineConfig config = ModuleMgr.getRtcEnginMgr().getEngineConfig();
        if (config.mChatType == AgoraConstant.RTC_CHAT_VIDEO) {
            RtcUIShow.showRtcVideoActNoCheck(App.activity);
            return;
        }
        RtcUIShow.showRtcVoiceAct(App.activity);
    }

    /**
     * 初始化引擎通信参数配置
     *
     * @param dstUid     对方UID
     * @param inviteType 1邀请，2受邀
     */
    private EngineConfig initEnginConfig(long dstUid, int inviteType) {
        ModuleMgr.getRtcEnginMgr().releaseEngineConfig();
        EngineConfig config = ModuleMgr.getRtcEnginMgr().getEngineConfig();
        config.mOtherId = dstUid;
        config.mChatType = chatType;
        config.mInviteType = inviteType;
        config.mCamera = singleType;
        return config;
    }

    /**
     * 男号：检测是否有权限发起聊天
     * 女号：检测对方是否可以聊天
     */
    private void reqChatQualified(long dstuid, RequestComplete complete) {
        Map<String, Object> postParams = new HashMap<>();
        postParams.put("gender", ModuleMgr.getCenterMgr().getMyInfo().getGender());
        postParams.put("uid_to", dstuid);
        ModuleMgr.getHttpMgr().reqPostNoCacheHttp(UrlParam.reqChatQualified, postParams, complete);
    }

    /**
     * 接受视频聊天请求
     *
     * @param dstUid  好友uid
     * @param msgType 音视频类型
     */
    public void reqAcceptVideoChat(long dstUid, int msgType, RequestComplete complete) {
        Map<String, Object> postParams = new HashMap<>();
        postParams.put("gender", ModuleMgr.getCenterMgr().getMyInfo().getGender());
        postParams.put("uid_to", dstUid);
        postParams.put("type_chat", msgType);
        ModuleMgr.getHttpMgr().reqPostNoCacheHttp(UrlParam.reqAcceptChat, postParams, complete);
    }

    /**
     * 加入频道成功，通知服务端
     */
    public void reqChatStart(long vcId, long dstUid, RequestComplete complete) {
        Map<String, Object> postParams = new HashMap<>();
        postParams.put("uid_girl", dstUid);
        postParams.put("id_rec_chat", vcId);
        ModuleMgr.getHttpMgr().reqPostNoCacheHttp(UrlParam.reqChatStart, postParams, complete);
    }

    /**
     * 挂断视频聊天请求
     */
    public void reqStopVideoChat(long vcId, RequestComplete complete) {
        if (vcId <= 0) return;
        Map<String, Object> postParams = new HashMap<>();
        postParams.put("id_rec_chat", vcId);
        ModuleMgr.getHttpMgr().reqPostNoCacheHttp(UrlParam.reqStopChat, postParams, complete);
    }

    /**
     * 视频聊天中，客户端刷新视频聊天状态（轮询接口）
     */
    public void reqCheckVideoChat(long vcId, RequestComplete complete) {
        if (vcId <= 0) return;
        Map<String, Object> postParams = new HashMap<>();
        postParams.put("id_rec_chat", vcId);
        ModuleMgr.getHttpMgr().reqPostNoCacheHttp(UrlParam.reqCheckChat, postParams, complete);
    }

    /**
     * 女性：抢聊大厅聊天池
     */
    public void reqChatPool(RequestComplete complete) {
        ModuleMgr.getHttpMgr().reqGetNoCacheHttp(UrlParam.reqChatPool, null, complete);
    }

    /**
     * 女性：抢占聊天
     */
    public void reqChatGrab(long vcId, RequestComplete complete) {
        Map<String, Object> postParams = new HashMap<>();
        postParams.put("id_rec_chat", vcId);
        ModuleMgr.getHttpMgr().reqPostNoCacheHttp(UrlParam.reqChatGrab, postParams, complete);
    }

    /**
     * 男性：发起群聊
     */
    public void reqChatAdd(RequestComplete complete) {
        Map<String, Object> postParams = new HashMap<>();
        postParams.put("type_chat", 2);     // 类型 1：语音 2:视频
        postParams.put("type_look", 1);     // 聊天类型 默认公开的 公开的=1，私人的=2
        ModuleMgr.getHttpMgr().reqPostNoCacheHttp(UrlParam.reqChatAdd, postParams, complete);
    }

    /**
     * 男性：取消发起群聊
     */
    public void reqChatCancel(long vcId, RequestComplete complete) {
        Map<String, Object> postParams = new HashMap<>();
        postParams.put("id_rec_chat", vcId);
        ModuleMgr.getHttpMgr().reqPostNoCacheHttp(UrlParam.reqChatCancel, postParams, complete);
    }

    /**
     * 发送拒绝音视频通话
     */
    public void sendRejectMsg(long whisperId, int msgType, SendCallBack sendCallBack) {
        CommonMessage commonMessage = new CommonMessage();
        commonMessage.setUidTo(whisperId);
        msgType = msgType == AgoraConstant.RTC_CHAT_VIDEO ? MessageConstant.MSG_ID_REJECT_VIDEO :
                MessageConstant.MSG_ID_REJECT_AUDIO;
        commonMessage.setMsgType(msgType);
        ModuleMgr.getChatMgr().sendMessage(commonMessage, sendCallBack);
        MsgMgr.getInstance().sendMsg(MsgType.MT_Rtc_Chat_Close_Msg, null);
    }

    /**
     * 发送音视频通话挂断消息
     */
    public void sendHangUpMsg(SendCallBack sendCallBack) {
        long whisperId = ModuleMgr.getRtcEnginMgr().getEngineConfig().mOtherId;
        int msgType = ModuleMgr.getRtcEnginMgr().getEngineConfig().mChatType;

        CommonMessage commonMessage = new CommonMessage();
        commonMessage.setUidTo(whisperId);
        commonMessage.setMsgType(msgType == AgoraConstant.RTC_CHAT_VOICE ? MessageConstant.MSG_ID_STOP_AUDIO : MessageConstant.MSG_ID_STOP_VIDEO);
        ModuleMgr.getChatMgr().sendMessage(commonMessage, sendCallBack);
    }

    /**
     * 发送用户忙消息
     */
    public void sendUserBusyMsg(long whisperId, SendCallBack sendCallBack) {
        CommonMessage commonMessage = new CommonMessage();
        commonMessage.setUidTo(whisperId);
        commonMessage.setMsgType(MessageConstant.MSG_USER_BUSY);
        ModuleMgr.getChatMgr().sendMessage(commonMessage, sendCallBack);
    }

    /**
     * 发送用户空闲
     */
    public void sendUserFreeMsg(long whisperId, SendCallBack sendCallBack) {
        CommonMessage commonMessage = new CommonMessage();
        commonMessage.setUidTo(whisperId);
        commonMessage.setMsgType(MessageConstant.MSG_USER_FREE);
        ModuleMgr.getChatMgr().sendMessage(commonMessage, sendCallBack);
    }

    /**
     * 随机获取女聊昵称头像
     */
    public void reqGirlRand(RequestComplete complete) {
        ModuleMgr.getHttpMgr().reqGetNoCacheHttp(UrlParam.reqGirlRand, null, complete);
    }

    // ====================== 抢聊： 自定义消息 ===============================

    /**
     * 男性：发送当前占线给抢夺女性
     */

    private void sendRobMsg(long whisperID, long mVcid, String cName, String cKey, int type, SendCallBack sendCallBack) {
        RobMessage msg = new RobMessage(mVcid, cName, cKey);
        msg.setUidTo(whisperID);
        msg.setMsgType(type);
        ModuleMgr.getChatMgr().sendMessage(msg, sendCallBack);
    }

    // ====================== 音视频相关接口 ===============================

    /**
     * 获取视频评价信息: 男方调用
     */
    public void reqGetFeedbackInfo(RequestComplete complete) {
        ModuleMgr.getHttpMgr().reqGetAndCacheHttp(UrlParam.reqGetFeedbackInfo, null, complete);
    }

    /**
     * 提交评价： 男方调用
     */
    public void reqAddFeedback(int star, List<String> reasons, RequestComplete complete) {
        Map<String, Object> postParams = new HashMap<>();
        postParams.put("id_rec_chat", ModuleMgr.getRtcEnginMgr().getEngineConfig().mVcid);
        postParams.put("star", star);
        postParams.put("labels", JSON.toJSONString(reasons));
        ModuleMgr.getHttpMgr().reqPostNoCacheHttp(UrlParam.reqAddFeedback, postParams, complete);
    }

    //  ============================================================== 以下暂时保留 ============================================

    /**
     * 视频聊天鉴黄接口
     *
     * @param url 图片地址
     */
    public void reqCheckPornography(long vcid, String url, RequestComplete complete) {
        Map<String, Object> postParams = new HashMap<>();
        postParams.put("vc_id", vcid);
        postParams.put("img_url", url);
        ModuleMgr.getHttpMgr().reqPostNoCacheHttp(UrlParam.reqCheckPornography, postParams, complete);
    }
}
